package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.*;
import com.jiyinit.web.core.business.entity.TabCoreTask;
import com.jiyinit.web.core.business.entity.TabCoreTaskMessage;
import com.jiyinit.web.core.business.entity.TabCoreUserTask;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.business.enums.SystemConstant;
import com.jiyinit.web.core.business.service.DailyLogServiceImpl;
import com.jiyinit.web.core.business.service.TaskMessageServiceImpl;
import com.jiyinit.web.core.business.service.UserTaskServiceImpl;
import com.jiyinit.web.core.business.vo.DailyLogListVo;
import com.jiyinit.web.core.business.vo.NoticeVo;
import com.jiyinit.web.core.business.vo.TaskInfoVo;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.MessagePush;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lr on 2017/12/27.
 */
@Controller
@RequestMapping("/mobile/dailyLog")
public class MdailyLogController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MdailyLogController.class);

    @Resource(name ="core.dailyLogService")
    private DailyLogServiceImpl dailyLogService;

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.userTaskServiceImpl")
    private UserTaskServiceImpl userTaskService;

    @Resource(name = "core.taskMessageServiceImpl")
    private TaskMessageServiceImpl taskMessageService;

    /**
     * 列表查询 我参与的工作日志
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "dailyLogList")
    public ResponseEntity<ResponseDto> dailyLogList(HttpServletRequest request) {
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/dailyLogList");
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        if (dailyLogRequest.getUserId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("用户不能为空"), HttpStatus.OK);
        }
        //自己的工作日志
        DailyLogListVo myVo = new DailyLogListVo();
        TabCoreTask dailyLog =  dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
        if(dailyLog != null){
            List<TaskInfoVo> myTaskList = new ArrayList<>();
            TaskInfoVo vo = new TaskInfoVo();
            BeanUtils.copyProperties(dailyLog,vo);
            myTaskList.add(vo);
            List<TabCoreTaskMessage> myMeList = taskMessageService.findNewMessageList(myTaskList);
            myVo.setTaskId(dailyLog.getTaskId());
            myVo.setCreateTime(dailyLog.getCreateTime());
            myVo.setMessage(myMeList);
            myVo.setAvatar(dailyLog.getAvatar());
        }

        PagingResult<TaskInfoVo> list = dailyLogService.receiveDailyLogList(dailyLogRequest);
        List<DailyLogListVo> resultList = new ArrayList<>();
        List<TabCoreTaskMessage> meList = null;
        if(list.getRows() != null && list.getRows().size() >0)
            meList = taskMessageService.findNewMessageList(list.getRows());

        for(TaskInfoVo task : list.getRows()){
            DailyLogListVo vo = new DailyLogListVo();
            vo.setTaskId(task.getTaskId());
            vo.setCreateTime(task.getCreateTime());
            vo.setUserName(task.getUserName());
            vo.setIsRead(task.getIsRead());
            List<TabCoreTaskMessage> messageList = new ArrayList<>();
            for(TabCoreTaskMessage message: meList){
                if(task.getTaskId().intValue() == message.getTaskId().intValue()){
                    messageList.add(message);
                }
            }
            vo.setMessage(messageList);
            vo.setAvatar(task.getAvatar());
            resultList.add(vo);
        }

        PagingResult<DailyLogListVo> receiveResult = new PagingResult<>();
        receiveResult.setTotalPages(list.getTotalPages());
        receiveResult.setTotalRecords(list.getTotalRecords());
        receiveResult.setCurrentPage(list.getCurrentPage());
        receiveResult.setRows(resultList);

        HashMap<String,Object> result = new HashMap<>();
        result.put("publish",myVo);
        result.put("receiveList",receiveResult);
        LogUtil.info(LOGGER, "接口:/mobile/dailyLog/dailyLogList,返回结果{}", JsonEntityTransform.object2Json(result));
        return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
    }

    /**
     * 我关注的人员列表 我不关注的人员列表
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "follow")
    public ResponseEntity<ResponseDto> follow(HttpServletRequest request) {
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/follow");
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        if (dailyLogRequest.getUserId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("用户不能为空"), HttpStatus.OK);
        }

        List<UserTaskVo> list = userTaskService.findUsers(dailyLogRequest.getUserId());

        List<UserTaskVo> follow =  new ArrayList<>();
        List<UserTaskVo> noFollow =  new ArrayList<>();
        for (UserTaskVo user:list){
            if(user.getIsPush().intValue() ==1){
                follow.add(user);
            }else{
                noFollow.add(user);
            }
        }
        HashMap<String,Object> result = new HashMap<>();
        result.put("follow",follow);
        result.put("noFollow",noFollow);
        LogUtil.info(LOGGER, "接口:/mobile/dailyLog/follow,返回结果{}", JsonEntityTransform.object2Json(result));
        return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
    }

    /**
     * 新建前的查询，该用户是否存在工作日志，不存在返回，存在则返回今天的工作日志的内容
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "checkAdd")
    public ResponseEntity<ResponseDto> checkAdd(HttpServletRequest request) {
        try {
            LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/checkAdd");
            DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
            if (dailyLogRequest.getUserId() == null) {
                return new ResponseEntity<>(ResponseDto.responseFail("用户不能为空"), HttpStatus.OK);
            }

            TabCoreTask task = dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
            HashMap<String,Object> result = new HashMap<>();
            result.put("dailyLog",task);
            //联系人，今天的说说
            TabCoreTaskMessage message = null;
            List<UserTaskVo> alltors = null;
            if(task != null){
                UserTaskRequest userTaskRequest = new UserTaskRequest();
                userTaskRequest.setTaskId(task.getTaskId());
                alltors = userTaskService.finAll(userTaskRequest);
                message = taskMessageService.findTodayMessage(task.getTaskId());
            }
            result.put("alltors",alltors);
            result.put("message",message);

            LogUtil.info(LOGGER, "接口:/mobile/dailyLog/checkAdd,返回结果{}", JsonEntityTransform.object2Json(result));
            return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
        }
        catch (Exception ex)
        {
            LogUtil.info(LOGGER, "接口:/mobile/dailyLog/checkAdd,访问异常{}", ex.toString());
            return new ResponseEntity<>( ResponseDto.responseFail("接口请求异常"), HttpStatus.OK);
        }
    }

    /**
     * 推送的开关
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "pushSwitch")
    public ResponseEntity<ResponseDto> pushSwitch(HttpServletRequest request) {
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/pushSwitch");
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        if (dailyLogRequest.getAlloterId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("用户不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getIsPush() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("推送开关不能为空"), HttpStatus.OK);
        }
        TabCoreTask  task = dailyLogService.getDailyLogByUserId(dailyLogRequest.getAlloterId());
        if(task == null){
            return new ResponseEntity<>( ResponseDto.responseFail("工作日志不存在"), HttpStatus.OK);
        }
        if(task.getCreateUid().intValue() == dailyLogRequest.getUserId().intValue()){ //工作日志的创建者，不存在推送开关
            return new ResponseEntity<>( ResponseDto.responseFail("创建者不存在推送开关"), HttpStatus.OK);
        }
        dailyLogRequest.setId(task.getTaskId());
        int num = userTaskService.pushSwitch(dailyLogRequest);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("推送开关更新失败"), HttpStatus.OK);
    }

    /**
     * 变更联系人
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "updateDailyLogAlloters")
    public ResponseEntity<ResponseDto> updateDailyLogAlloters(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/updateDailyLogAlloters");
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        if (dailyLogRequest.getUserId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("用户不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("ID不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getAlloterIds() == null && dailyLogRequest.getAlloterIds().length<= 0) {
            return new ResponseEntity<>(ResponseDto.responseFail("参与者不能为空"), HttpStatus.OK);
        }

        int num = userTaskService.updateDailyLogAlloters(dailyLogRequest);
        if(num > 0) {
            //极光推送
            Map<String,String> returnStr = new HashMap<>();
            TabCoreTask tabCoreTask = dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
            if(tabCoreTask!=null)
            {
                returnStr.put("taskTitle", tabCoreTask.getTitle());
                returnStr.put("taskId", tabCoreTask.getTaskId().toString());
                returnStr.put("createUid", String.valueOf(tabCoreTask.getCreateUid()));
                returnStr.put("strikeType", "2");
                returnStr.put("type", OperationTypeConstant.DAILYLOG_CHANGE_PERSON);
                returnStr.put("dsc", tabCoreTask.getDescription());
                returnStr.put("taskStatus",tabCoreTask.getStatus());
                returnStr.put("content","日志："+tabCoreTask.getTitle()+"，变更参与人");
                returnStr.put("taskCla", String.valueOf(SystemConstant.DAILY_LOG));

                Integer[] alloterIds=dailyLogRequest.getAlloterIds();
                String[] array=new String[alloterIds.length];
                if(alloterIds!=null)
                {
                    for(int i=0;i<alloterIds.length;i++)
                    {
                        array[i]=String.valueOf(alloterIds[i]);
                    }
                }
                if(dailyLogRequest.getChannel()!=null&&dailyLogRequest.getChannel().equals("01")){
                    MessagePush messagePush = new MessagePush(returnStr,array);
                }else{
                    MessagePush messagePush = new MessagePush(returnStr,array,"andriod");
                }
                //极光推送结束
            }

            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>( ResponseDto.responseFail("更新失败！"), HttpStatus.OK);
    }
    /**
     * 添加工作日志
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "add")
    public ResponseEntity<ResponseDto> add(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/add");
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        if (dailyLogRequest.getChannel() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("渠道不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getAlloterIds() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("联系人不能为空"), HttpStatus.OK);
        }
        if (dailyLogRequest.getTitle() == null && "".equals(dailyLogRequest.getTitle())) {
            return new ResponseEntity<>(ResponseDto.responseFail("标题不能为空"), HttpStatus.OK);
        }
        //每个人只能有一个工作日志
        TabCoreTask dailyLog =  dailyLogService.getDailyLogByUserId(dailyLogRequest.getUserId());
        if(dailyLog != null)  return new ResponseEntity<>( ResponseDto.responseFail("已存在工作日志！"), HttpStatus.OK);

        int num = dailyLogService.add(dailyLogRequest);
        if(num > 0)
        {
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }

     /**
     * 查看工作日志详细信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "detail")
    public ResponseEntity<ResponseDto> detail(HttpServletRequest request){
        DailyLogRequest dailyLogRequest = getJsonToTaskRequest(request);
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/detail");
        if (dailyLogRequest.getId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("ID不能为空"), HttpStatus.OK);
        }
        TabCoreTask dailyLog = dailyLogService.getDailyLogById(dailyLogRequest.getId());
        UserTaskRequest uses = new UserTaskRequest();
        uses.setTaskId(dailyLog.getTaskId());
        List<UserTaskVo> users = userTaskService.finAll(uses);

        HashMap<String,Object> result = new HashMap<>();
        result.put("dailyLog",dailyLog);
        result.put("alloters",users);

        LogUtil.info(LOGGER, "接口:/mobile/dailyLog/detail,返回结果{}", JsonEntityTransform.object2Json(result));

        if(dailyLog != null)
            return new ResponseEntity<>( ResponseDto.responseOK(result), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("查询详情失败！"), HttpStatus.OK);

    }
    /**
     * 添加工作日志说说（每天只有一条）
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "addMessage")
    public ResponseEntity<ResponseDto> addMessage(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/dailyLog/addMessage");
        String content = (String) request.getAttribute("request_json");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        MessageRequest messageRequest = (MessageRequest) JsonEntityTransform.json2Object(logJson, MessageRequest.class);
        if (messageRequest.getId() == null) {
            return new ResponseEntity<>(ResponseDto.responseFail("工作日志ID不能为空"), HttpStatus.OK);
        }
        if (messageRequest.getContent() == null && "".equals(messageRequest.getContent())) {
            return new ResponseEntity<>(ResponseDto.responseFail("说说内容不能为空"), HttpStatus.OK);
        }
        if (messageRequest.getContent().length()>500) {
            return new ResponseEntity<>(ResponseDto.responseFail("说说内容长度不能大于500"), HttpStatus.OK);
        }
        if (messageRequest.getIsPush()== null ) {
            return new ResponseEntity<>(ResponseDto.responseFail("是否推送不能为空"), HttpStatus.OK);
        }

        ValidateResult<MessageRequest> validateResult = paramCheckLogic.checkParamValidate(messageRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }

        int num = taskMessageService.addDailyLogMessage1(messageRequest);

        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""), HttpStatus.OK);
        return new ResponseEntity<>( ResponseDto.responseFail("新建失败！"), HttpStatus.OK);
    }



    private DailyLogRequest getJsonToTaskRequest(HttpServletRequest request){
        String content = (String) request.getAttribute("request_json");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        DailyLogRequest dailyLogRequest = (DailyLogRequest) JsonEntityTransform.json2Object(logJson, DailyLogRequest.class);
        return dailyLogRequest;
    }

}
